<template>
  <div class="process-container">
    <!-- 顶部操作栏 -->
    <div class="top-bar">
      <a-space>
        <a-button @click="goBack">
          <template #icon>
            <IconArrowLeft />
          </template>
          <template #default>返回</template>
        </a-button>
        <a-button
          :loading="approveLoading"
          type="primary"
          @click="showApproveModal"
        >
          <template #default>立即审批</template>
        </a-button>
      </a-space>
    </div>

    <!-- 审批内容 -->
    <div class="process-content" v-loading="loading">
      <!-- 申请基本信息 -->
      <a-card title="申请基本信息" class="mb-4">
        <a-descriptions
          :column="2"
          :label-style="{ width: '120px' }"
          :value-style="{ color: '#1d2129' }"
          bordered
          layout="inline-horizontal"
          size="medium"
        >
          <a-descriptions-item label="项目名称">
            {{ basicInfo.projectName || "-" }}
          </a-descriptions-item>
          <a-descriptions-item label="申请状态">
            <a-tag :color="getStatusColor(basicInfo.status)" size="large">
              {{ getStatusText(basicInfo.status) }}
            </a-tag>
          </a-descriptions-item>

          <a-descriptions-item label="申请编号">
            {{ subsidyApplicationId || "-" }}
          </a-descriptions-item>
          <a-descriptions-item label="申请时间">
            {{ basicInfo.createTime || "-" }}
          </a-descriptions-item>
          <a-descriptions-item label="验收时间">
            {{ basicInfo.acceptDate || "-" }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ basicInfo.updateTime || "-" }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 镇街明细 -->
        <a-divider orientation="left">镇街明细</a-divider>
        <div class="town-item-section">
          <div
            v-if="
              !basicInfo.subsidyApplicationTownItemList ||
              basicInfo.subsidyApplicationTownItemList.length === 0
            "
            class="empty-state"
          >
            <a-empty description="暂无镇街明细" />
          </div>
          <div v-else class="town-item-list">
            <a-table
              :data="basicInfo.subsidyApplicationTownItemList"
              :pagination="false"
              :bordered="true"
              size="medium"
              class="town-item-table"
            >
              <template #columns>
                <a-table-column title="序号" :width="100" align="center">
                  <template #cell="{ rowIndex }">
                    {{ rowIndex + 1 }}
                  </template>
                </a-table-column>
                <a-table-column
                  title="镇街名称"
                  data-index="townName"
                  :width="120"
                />
                <a-table-column
                  title="验收亩数"
                  data-index="acceptAcreage"
                  :width="100"
                  align="right"
                />
                <a-table-column
                  title="总金额(万元)"
                  data-index="totalAmount"
                  :width="120"
                  align="right"
                />
                <a-table-column
                  title="备注"
                  data-index="remark"
                  ellipsis
                  tooltip
                />
              </template>
            </a-table>

            <!-- 总计信息 -->
            <div
              class="town-summary"
              v-if="
                basicInfo.subsidyApplicationTownItemList &&
                basicInfo.subsidyApplicationTownItemList.length > 0
              "
            >
              <a-descriptions
                :column="2"
                :label-style="{ fontWeight: 'bold', color: '#1d2129' }"
                :value-style="{ fontWeight: 'bold', color: '#165dff' }"
                bordered
                size="medium"
              >
                <a-descriptions-item label="总验收亩数">
                  {{ townSummary.totalAcreage }}亩
                </a-descriptions-item>
                <a-descriptions-item label="总金额">
                  {{ townSummary.totalAmount }}万元
                </a-descriptions-item>
              </a-descriptions>
            </div>
          </div>
        </div>

        <!-- 申请附件 -->
        <a-divider orientation="left">申请附件</a-divider>
        <div class="attachment-section">
          <div v-if="filesByType.length === 0" class="empty-state">
            <a-empty description="暂无附件" />
          </div>
          <div v-else class="attachment-types">
            <div
              v-for="typeGroup in filesByType"
              :key="typeGroup.type"
              class="attachment-type-group"
            >
              <div class="type-header">
                <h4>{{ typeGroup.typeName }}</h4>
                <a-tag size="small">{{ typeGroup.files.length }}个文件</a-tag>
              </div>
              <div class="file-list">
                <div
                  v-for="(fileItem, index) in typeGroup.files"
                  :key="fileItem.id || index"
                  class="file-item"
                >
                  <div class="file-info">
                    <div class="file-name">
                      <a-link
                        :href="fileItem.file?.fileUrl"
                        target="_blank"
                        :hoverable="false"
                      >
                        {{ fileItem.file?.fileName || "未知文件" }}
                      </a-link>
                    </div>
                    <div class="file-meta">
                      <span class="file-size">
                        {{ formatFileSize(fileItem.file?.fileSize) }}
                      </span>
                      <span class="file-time">
                        上传时间: {{ fileItem.createTime || "-" }}
                      </span>
                    </div>
                  </div>
                  <div class="file-actions">
                    <a-button
                      type="text"
                      size="small"
                      @click="downloadFile(fileItem.file)"
                    >
                      下载
                    </a-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-card>

      <!-- 详细信息标签页 -->
      <a-card title="详细信息" class="mb-4">
        <a-tabs v-model:active-key="activeTab" type="line" size="large">
          <a-tab-pane v-if="false" key="payment-voucher" title="支付凭证">
            <PaymentVoucherManagement
              :subsidy-application-id="subsidyApplicationId"
              :readonly="true"
            />
          </a-tab-pane>

          <a-tab-pane key="payment-notice" title="支付通知">
            <PaymentNotice
              :subsidy-application-id="subsidyApplicationId"
              :readonly="false"
              :town-item-list="basicInfo.subsidyApplicationTownItemList || []"
            />
          </a-tab-pane>

          <a-tab-pane key="payment" title="付款管理">
            <PaymentManagement
              :subsidy-application-id="subsidyApplicationId"
              :readonly="true"
            />
          </a-tab-pane>

          <a-tab-pane v-if="false" key="approval" title="审批历史">
            <ApprovalHistory :subsidy-application-id="subsidyApplicationId" />
          </a-tab-pane>
        </a-tabs>
      </a-card>
    </div>

    <!-- 改进的审批弹窗 -->
    <a-modal
      v-model:visible="approveModalVisible"
      title="审批操作"
      width="600px"
      :footer="false"
      @cancel="resetApproveForm"
    >
      <div class="approve-modal-content">
        <a-form
          ref="approveFormRef"
          :model="approveForm"
          :rules="approveRules"
          layout="vertical"
        >
          <a-form-item field="approvalResult" label="审批结果" required>
            <a-radio-group v-model="approveForm.approvalResult" size="large">
              <a-radio value="approved">
                <template #radio="{ checked }">
                  <a-space>
                    <IconCheckCircle
                      :style="{ color: checked ? '#00b42a' : '' }"
                    />
                    <span>通过</span>
                  </a-space>
                </template>
              </a-radio>
              <a-radio value="rejected">
                <template #radio="{ checked }">
                  <a-space>
                    <IconCloseCircle
                      :style="{ color: checked ? '#f53f3f' : '' }"
                    />
                    <span>驳回</span>
                  </a-space>
                </template>
              </a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item
            v-if="approveForm.approvalResult === 'rejected'"
            field="approvalComment"
            label="审批意见"
            required
          >
            <a-textarea
              v-model="approveForm.approvalComment"
              :auto-size="{ minRows: 4, maxRows: 8 }"
              placeholder="请详细说明驳回理由..."
              show-word-limit
              :max-length="500"
            />
          </a-form-item>

          <!-- 审批操作按钮 -->
          <div class="approve-actions">
            <a-space size="large">
              <a-button size="large" @click="resetApproveForm">取消</a-button>
              <a-button
                type="primary"
                size="large"
                :loading="approveLoading"
                @click="handleApprove"
                :disabled="
                  !approveForm.approvalResult ||
                  (approveForm.approvalResult === 'rejected' &&
                    !approveForm.approvalComment)
                "
              >
                确认审批
              </a-button>
            </a-space>
          </div>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import {
  computed,
  defineProps,
  defineEmits,
  getCurrentInstance,
  onMounted,
  reactive,
  ref,
  watch,
} from "vue";
import { Message, Modal } from "@arco-design/web-vue";
import {
  IconArrowLeft,
  IconCheckCircle,
  IconCloseCircle,
  IconDown,
} from "@arco-design/web-vue/es/icon";
// 导入API方法
import { getSubsidyApplicationBySubsidyApplicationIdApi } from "~/api/lindi/subsidyApplication.js";
import { approveSubsidyApplicationApi } from "~/api/lindi/subsidyApplicationApproval.js";
// 导入字典工具
import { DICT } from "~/utils/dict.js";

// 导入子组件
import BasicInfoView from "./components/BasicInfoView.vue";
import SubsidyFiles from "./components/SubsidyFiles.vue";
import PaymentNotice from "./components/PaymentNotice.vue";
import PaymentManagement from "./components/PaymentManagement.vue";
import PaymentVoucherManagement from "./components/PaymentVoucherManagement.vue";
import ApprovalHistory from "./components/ApprovalHistory.vue";

// 定义props
const props = defineProps({
  subsidyApplicationId: {
    type: String,
    default: "",
  },
});

// 定义事件
const emit = defineEmits(["cancel", "approved"]);

// 全局实例
const { proxy } = getCurrentInstance();

// 加载字典数据
const dicts = proxy.LoadDicts([DICT.lindiSubsidyApplicationStatus]);

// 响应式数据
const loading = ref(false);
const approveLoading = ref(false);
const approveModalVisible = ref(false);
const approveFormRef = ref(null);
const activeTab = ref("payment-notice");
const infoExpanded = ref(false);
const currentStep = ref(1);
const activeKeys = ref([]);

// 基础信息数据
const basicInfo = ref({});

// 附件列表数据
const fileList = ref([]);

// 文件类型映射
const fileTypeMap = {
  0: "建设方案文件",
  1: "验收意见文件",
  2: "支付通知文件",
  3: "付款记录文件",
};

// 按类型分组的文件列表
const filesByType = computed(() => {
  if (!fileList.value || fileList.value.length === 0) {
    return [];
  }

  // 按文件类型分组
  const grouped = fileList.value.reduce((acc, file) => {
    const type = file.fileType || "0";
    if (!acc[type]) {
      acc[type] = [];
    }
    acc[type].push(file);
    return acc;
  }, {});

  // 转换为数组格式，按类型顺序排列
  const typeOrder = ["0", "1", "2", "3"];
  return typeOrder
    .filter((type) => grouped[type] && grouped[type].length > 0)
    .map((type) => ({
      type,
      typeName: fileTypeMap[type] || "其他文件",
      files: grouped[type],
    }));
});

// 镇街明细总计信息
const townSummary = computed(() => {
  const townItemList = basicInfo.value.subsidyApplicationTownItemList || [];

  if (townItemList.length === 0) {
    return {
      totalAcreage: "0",
      totalAmount: "0",
    };
  }

  const totalAcreage = townItemList.reduce((sum, item) => {
    const acreage = parseFloat(item.acceptAcreage) || 0;
    return sum + acreage;
  }, 0);
  const totalAmount = townItemList.reduce((sum, item) => {
    const amount = parseFloat(item.totalAmount) || 0;
    return sum + amount;
  }, 0);

  return {
    totalAcreage: totalAcreage.toFixed(2),
    totalAmount: totalAmount.toFixed(2),
  };
});

// 审批表单
const approveForm = reactive({
  approvalResult: "",
  approvalComment: "",
});

// 审批表单规则
const approveRules = {
  approvalResult: [{ required: true, message: "请选择审批结果" }],
  approvalComment: [
    {
      required: true,
      message: "请输入驳回理由",
      validator: (value, callback) => {
        if (approveForm.approvalResult === "rejected" && !value) {
          callback("请输入驳回理由");
        } else if (
          approveForm.approvalResult === "rejected" &&
          value &&
          value.length < 5
        ) {
          callback("驳回理由至少5个字符");
        } else {
          callback();
        }
      },
    },
  ],
};

// 返回列表页
const goBack = () => {
  emit("cancel");
};

// 显示审批弹窗
const showApproveModal = () => {
  approveModalVisible.value = true;
};

// 处理审批
const handleApprove = () => {
  // 如果是通过，直接处理；如果是驳回，需要验证表单
  if (approveForm.approvalResult === "approved") {
    submitApproval();
  } else {
    approveFormRef.value.validate((errors) => {
      if (errors) {
        return;
      }
      submitApproval();
    });
  }
};

// 提交审批
const submitApproval = () => {
  approveLoading.value = true;

  // 构建审批数据
  const approvalData = {
    subsidyApplicationId: props.subsidyApplicationId,
    approvalResult: approveForm.approvalResult === "approved" ? 1 : 2, // 1-通过，2-驳回
    approvalComment:
      approveForm.approvalResult === "approved"
        ? "审批通过"
        : approveForm.approvalComment,
    updateId: proxy.$store.getters.userId, // 当前用户ID
    updateTime: new Date().toISOString().replace("T", " ").substring(0, 19),
  };

  // 调用审批API
  approveSubsidyApplicationApi(approvalData)
    .then((res) => {
      console.log("审批操作成功:", res);
      Message.success(
        approveForm.approvalResult === "approved"
          ? "审批通过成功"
          : "审批驳回成功"
      );
      approveModalVisible.value = false;
      emit("approved", {
        subsidyApplicationId: props.subsidyApplicationId,
        ...approveForm,
      });
      // 重新加载基础信息以更新状态
      loadBasicInfo();
    })
    .catch((error) => {
      console.error("审批操作失败:", error);
      Message.error("审批操作失败，请稍后重试");
    })
    .finally(() => {
      approveLoading.value = false;
    });
};

// 切换信息展开状态
const toggleInfoExpand = () => {
  infoExpanded.value = !infoExpanded.value;
  activeKeys.value = infoExpanded.value ? ["basic"] : [];
};

// 获取状态颜色
const getStatusColor = (status) => {
  if (!status || !dicts[DICT.lindiSubsidyApplicationStatus]) {
    return "gray";
  }
  const dict = dicts[DICT.lindiSubsidyApplicationStatus].find(
    (d) => String(d.dictKey) === String(status)
  );
  return dict?.dictClass || "gray";
};

// 获取状态文本
const getStatusText = (status) => {
  if (!status || !dicts[DICT.lindiSubsidyApplicationStatus]) {
    return "未知状态";
  }
  const dict = dicts[DICT.lindiSubsidyApplicationStatus].find(
    (d) => String(d.dictKey) === String(status)
  );
  return dict ? dict.dictValue : "未知状态";
};

// 重置审批表单
const resetApproveForm = () => {
  approveForm.approvalResult = "";
  approveForm.approvalComment = "";
  approveModalVisible.value = false;
};

// 格式化文件大小
const formatFileSize = (size) => {
  if (!size) return "-";
  const sizeNum = parseInt(size);
  if (sizeNum < 1024) {
    return sizeNum + " B";
  } else if (sizeNum < 1024 * 1024) {
    return (sizeNum / 1024).toFixed(1) + " KB";
  } else {
    return (sizeNum / (1024 * 1024)).toFixed(1) + " MB";
  }
};

// 下载文件
const downloadFile = (file) => {
  if (file?.fileUrl) {
    window.open(file.fileUrl, "_blank");
  } else {
    Message.error("文件链接不存在");
  }
};

// 加载基础信息
const loadBasicInfo = () => {
  if (!props.subsidyApplicationId) {
    return;
  }
  loading.value = true;

  getSubsidyApplicationBySubsidyApplicationIdApi(props.subsidyApplicationId)
    .then((res) => {
      console.log("获取补贴申请详情成功:", res);

      // 设置基础信息
      basicInfo.value = {
        ...res,
        status: res.subsidyStatus || "SUBMITTED",
        createTime: res.createTime || "",
        submitter:
          res.submitter || res.enterpriseAccount?.enterprisePerson || "",
        enterpriseName:
          res.enterpriseAccount?.enterpriseName || res.enterpriseName || "",
        projectName: res.projectName || "",
        subsidyArea: res.subsidyArea || "",
        acceptanceTime: res.acceptanceTime || "",
        subsidyApplicationTownItemList:
          res.subsidyApplicationTownItemList || [],
      };

      // 设置附件列表
      fileList.value = res.subsidyApplicationFileList || [];

      // 根据状态设置当前步骤
      const stepMap = {
        SUBMITTED: 0,
        FORESTRY_PENDING: 1,
        FORESTRY_APPROVED: 2,
        ONLINE_CONFIRMED: 2,
        PAYMENT_PROCESSING: 3,
        PAYMENT_COMPLETED: 4,
        COMPLETED: 4,
      };
      currentStep.value = stepMap[res.status] || 0;
    })
    .catch((error) => {
      console.error("获取补贴申请详情失败:", error);
      Message.error("获取补贴申请详情失败，请稍后重试");
    })
    .finally(() => {
      loading.value = false;
    });
};

// 组件挂载时加载数据
onMounted(() => {
  loadBasicInfo();
});

// 监听subsidyApplicationId变化
watch(
  () => props.subsidyApplicationId,
  (newId) => {
    if (newId) {
      loadBasicInfo();
    }
  },
  { immediate: true }
);
</script>

<style scoped>
.process-container {
  padding: 16px;
  background-color: #f7f8fa;
  min-height: 100vh;
}

.top-bar {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.process-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.mb-4 {
  margin-bottom: 16px;
}

.mb-4:last-child {
  margin-bottom: 0;
}

.approve-modal-content .approve-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #e5e6eb;
}

/* 附件区域样式 */
.attachment-section {
  margin-top: 16px;
}

.attachment-types {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.attachment-type-group {
  border: 1px solid #e5e6eb;
  border-radius: 8px;
  overflow: hidden;
}

/* 镇街明细样式 */
.town-item-section {
  margin-top: 16px;
}

.town-item-table {
  margin-top: 8px;
}

.town-item-table :deep(.arco-table-th) {
  background-color: #f7f8fa;
  font-weight: 600;
}

.town-item-table :deep(.arco-table-td) {
  padding: 12px 16px;
}

/* 总计信息样式 */
.town-summary {
  margin-top: 16px;
  padding: 16px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-radius: 8px;
  border: 1px solid #bae6fd;
}

.town-summary :deep(.arco-descriptions-item-label) {
  background-color: rgba(22, 93, 255, 0.1);
}

.town-summary :deep(.arco-descriptions-item-value) {
  background-color: rgba(22, 93, 255, 0.05);
}

.empty-state {
  padding: 24px;
  text-align: center;
  background-color: #fafafa;
  border-radius: 6px;
  border: 1px dashed #d9d9d9;
}

.type-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #f7f8fa;
  border-bottom: 1px solid #e5e6eb;
}

.type-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
  color: #1d2129;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 0;
}

.attachment-type-group .file-list {
  background: #fff;
}

.attachment-type-group .file-item {
  border-radius: 0;
  border: none;
  border-bottom: 1px solid #e5e6eb;
  background: #fff;
}

.attachment-type-group .file-item:last-child {
  border-bottom: none;
}

.attachment-type-group .file-item:hover {
  background: #f2f3ff;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: #f7f8fa;
  border-radius: 8px;
  border: 1px solid #e5e6eb;
  transition: all 0.2s;
}

.file-item:hover {
  border-color: #165dff;
  background: #f2f3ff;
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
  word-break: break-all;
}

.file-name .arco-link {
  color: #1d2129;
  text-decoration: none;
}

.file-name .arco-link:hover {
  color: #165dff;
  text-decoration: underline;
}

.file-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #86909c;
}

.file-actions {
  flex-shrink: 0;
  margin-left: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .process-container {
    padding: 12px;
  }

  .top-bar {
    padding: 12px;
  }

  .top-bar .arco-space {
    width: 100%;
    justify-content: stretch;
  }

  .top-bar .arco-btn {
    flex: 1;
  }

  .attachment-types {
    gap: 16px;
  }

  .type-header {
    padding: 8px 12px;
  }

  .type-header h4 {
    font-size: 13px;
  }

  .file-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .file-actions {
    margin-left: 0;
    align-self: flex-end;
  }

  .file-meta {
    flex-direction: column;
    gap: 4px;
  }
}
</style>
